package com.lib;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

public class BitmapCache {
	static BitmapCache bitmapCache = new BitmapCache();

	public static BitmapCache getCache() {
		return bitmapCache;
	}

	final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
	final int cacheSize = maxMemory / 8;
	
	LruCache<String, Bitmap> lc = new LruCache<String, Bitmap>(cacheSize) {

		@Override
		protected Bitmap create(String key) {
			String fileName = String.valueOf(key.hashCode());
			Bitmap result = null;
			File file = FileCache.getCache().get(fileName);
			if (file != null) {
				result = BitmapFactory.decodeFile(file.getAbsolutePath());
			}
			if (result == null)
				try {
					for (int i = 3; --i >= 0;) {
						URL url = new URL(key);
						HttpURLConnection conn = (HttpURLConnection) url
								.openConnection();
						conn.setRequestMethod("GET");
						InputStream is = conn.getInputStream();
						result = BitmapFactory.decodeStream(is);
						if (result != null) {
							file = FileCache.getCache().getFile(fileName);
							FileOutputStream fos = new FileOutputStream(file);
							result.compress(CompressFormat.PNG, 100, fos);
							fos.close();
							FileCache.getCache().put(fileName, file);
							break;
						}
					}
				} catch (Throwable t) {
					t.printStackTrace();
				}
			return result;
		}

		@Override
		protected int sizeOf(String key, Bitmap value) {
			return value.getRowBytes() * value.getHeight();
		}

	};

	public Bitmap getBitmap(String key) {
		return lc.get(key);
	}

	public void remove(String key) {
		// 删除内存
		Bitmap bitmap = lc.remove(key);
		if (bitmap != null && !bitmap.isRecycled()) {
			bitmap.recycle();
		}
	}

	/**
	 * 清空内存和sdcard 的图片缓存
	 * 
	 * @param key
	 */
	public BitmapCache removeMemeryAndSdcard(String key) {
		// 删除内存
		Bitmap bitmap = lc.remove(key);
		if (bitmap != null && !bitmap.isRecycled()) {
			bitmap.recycle();
		}
		// 删除sdcard
		String fileName = String.valueOf(key.hashCode());
		File file = FileCache.getCache().get(fileName);
		if (file != null && file.exists()) {
			file.delete();
		}
		return this;
	}
}


